<?php

namespace app\api\controller;

use app\api\model\Oauth;
use app\common\controller\Send;
use app\common\enums\StatusEnum;
use think\Controller;
use app\api\model\OauthSession;
use think\facade\Request;


class Base extends Controller
{
    use Send;

    public $tokenValue;
    public $oauthInfo;
    public $pageSize;

    /**
     * @throws \think\Exception\DbException
     */
    public function initialize()
    {

        $needToken = input('needToken');

        $time = $this->get_runtime();
        $ip = request()->ip();
        $url = request()->url(true);

//        $http = "http://ip-api.com/json/$ip?lang=zh-CN";
//        $address = file_get_contents($http);
//        $address = json_decode($address,true);
//        if ($address['status']== 'success') {
//            $country = $address['country'];
//            $regionName = $address['regionName'];
//        } else {
//            $country = 0;
//            $regionName = 0;
//        }




        if($needToken == "" || $needToken != 0){
            // 登录验证
            $this->certification();
        }
        
        
        // 分页条数
        $this->pageSize = config('app.setting.page_size');
    }

    /**
     * 登录验证
     * @throws \think\Exception\DbException
     */
    public function certification()
    {
        $data['token'] = input('token');

        // 检测变量
        $validate = new \app\api\validate\Base();
        
        if (!$validate->check($data)) {
            
            $oauthSession = OauthSession::getSessionByToken($data['token']);

            if(empty($oauthSession)){
                self::exitJson(self::sendResult(104, [], "您的账号在其他手机登录过，请重新登录"));
            }else if($oauthSession['overtime'] <= time()){
                self::exitJson(self::sendResult(104, [], $validate->getError()));
            }else{
                
                $this->tokenValue = $oauthSession['oauth_id'];
                cache($data['token'], $oauthSession['oauth_id'], 8640000);

            }
            
        }

        // token存储的用户信息
        $this->tokenValue = json_decode(cache($data['token']), true);

        //如果是小程序的则获取array
        $token = empty($this->tokenValue['openid']) ? $this->tokenValue : $this->tokenValue['uid'];
        if($token){
            // 授权数据
            //$openid = $this->tokenValue['openid'];
            $oauth = Oauth::getOne($token);
            
            if (empty($oauth)) {
                self::exitJson(self::sendResult(107));
            }
            
            // 账号被冻结
            if ($oauth['status'] != StatusEnum::ENABLED) {
                self::exitJson(self::sendResult(108));
            }
            
            // 存储用户信息
            $this->oauthInfo = $oauth;
            
        }
        
    }
    /**
     * 得到当前时间
     */
    function get_runtime(){ $ntime=microtime(true); $total=$ntime-$GLOBALS['_beginTime']; return round($total,4); }

    public static   function debugLog($msg) {
        $fileName = "address_" . date('Ymd', time()) . ".log";
        self::writeLog($msg, $fileName);
    }



    public static function writeLog($msg, $fileName) {
        $filePath = '/data/web/boxueteach.com/address_logs/';
        $file = $filePath . $fileName;
        if (!file_exists($filePath)) {
            mkdir($filePath, '0777', true);
        }
        if (is_writable(dirname($file))) {
            if (!is_string($msg)) {
                $msg = var_export($msg, TRUE);
            }
            file_put_contents($file, "#" . date('Y-m-d H:i:s') . $msg . "\r\n", FILE_APPEND);
        }
    }

}
